import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:tender_flutter/constant/app_constant.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/dialog/place_top_combo_dialog.dart';
import 'package:tender_flutter/dialog/place_top_dialog.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/common/api/api_common.dart';
import 'package:tender_flutter/page/common/model/upload_result_entity.dart';
import 'package:tender_flutter/page/home/api/api_home.dart';
import 'package:tender_flutter/page/home/model/combo_top_entity.dart';
import 'package:tender_flutter/page/home/model/common_tag_model.dart';
import 'package:tender_flutter/page/home/model/publish_result_entity.dart';
import 'package:tender_flutter/page/person/model/pay_params.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/utils/img_picker.dart';
import 'package:tender_flutter/utils/picker.dart';
import 'package:tender_flutter/utils/regex_util.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/utils/utils.dart';
import 'package:tender_flutter/widgets/form_widget/form_multiple_input_item.dart';
import 'package:tender_flutter/widgets/form_widget/form_option_item.dart';

class MarketPublishFormPage extends StatefulWidget {
  /// 供需类型 参见 AppConstant
  final int marketType;

  const MarketPublishFormPage({Key key, this.marketType}) : super(key: key);

  @override
  _MarketPublishFormPageState createState() => _MarketPublishFormPageState();
}

class _MarketPublishFormPageState extends State<MarketPublishFormPage>
    with AutomaticKeepAliveClientMixin {
  GlobalKey<FormState> _formKey = new GlobalKey<FormState>();

  /// [1：置顶、2：免费]选中的按钮标识 ，默认置顶
  int radioGroupValue = 1;

  /// 行业类别数据
  List<CommonTagModel> _industryDatas;

  /// 选择的图片文件
  List<File> _selectImageFile = [];

  /// 上传完成的图片urls
  List<String> _imageUrls = [];

  /// 标题
  String _title;

  /// 公司
  String _companyName;

  /// 姓名
  String _userName;

  /// 电话
  String _phone;

  /// 微信
  String _wechatNum;

  /// 行业
  String _industryName;

  /// 行业id
  int _industryId;

  /// 城市
  String _city;

  /// 城市id
  int _cityCode;

  /// 价格
  String _price;

  /// 备注内容
  String _content;

  /// 选中的置顶套餐
  ComboTopEntity _comboTopEntity;

  /// 发布
  Future _publishMarket() async {
    ToastUtils.showLoading("");

    _imageUrls.clear();

    /// 上传图片
    List<Future> uploadApis = _selectImageFile
        .map((e) => _uploadImage(e).then((value) => _imageUrls.add(value.url)))
        .toList();

    Future.wait(uploadApis).then((value) {
      _submitFormDatas().then((sValue) {
        ToastUtils.dismissLoading();
        if (sValue.status == Status.SUCCESS) {
          if (_comboTopEntity != null) {
            /// 需要置顶
            PayParams params = PayParams();
            params.goodsDes = "供需置顶";
            params.goodsId = sValue.result.id;
            params.comboId = _comboTopEntity.id;
            params.goodsPrice = _comboTopEntity.money;
            params.orderType = AppConstant.PAY_ORDER_MARKET_TOP;
            LRouter.navigatorCtx(context).push(Routes.paymentPage,
                arguments: PaymentPageArguments(payParams: params));
          } else {
            LRouter.navigatorCtx(context).popAndPush(Routes.publishSuccessPage);
          }
        }
      });
    }).catchError((e) {
      print(e.toString());
      ToastUtils.dismissLoading();
      ToastUtils.show("图片资源处理失败");
    });
  }

  /// 提交表单数据
  Future _submitFormDatas() {
    return ApiHome.publishMarket<PublishResultEntity>(
        type: widget.marketType,
        areaCode: _cityCode,
        title: _title,
        company: _companyName,
        userName: _userName,
        content: _content,
        infoType: widget.marketType,
        price: _price,
        wxAccount: _wechatNum,
        phone: _phone,
        pics: _imageUrls);
  }

  /// 获取行业类别
  Future _getIndustryCategory() async {
    if (_industryDatas != null && _industryDatas.isNotEmpty) {
      return;
    }
    var response =
        await ApiHome.getMarketIndustryCategory<List<CommonTagModel>>();
    _industryDatas = response.result;
    return;
  }

  /// 上传图片
  Future _uploadImage(File file) async {
    ApiResponse<UploadResultEntity> response =
        await ApiCommon.uploadImage([file]);
    return response.result;
  }

  /// 置顶弹窗
  Future showPlaceTopDialog() async {
    return await showGeneralDialog(
        context: context,
        pageBuilder: (context, anim1, anim2) {},
        barrierDismissible: true,
        barrierLabel: "",
        transitionDuration: Duration(milliseconds: 300),
        transitionBuilder: (context, anim1, anim2, child) {
          return Transform.scale(
              scale: anim1.value,
              child: Opacity(
                opacity: anim1.value,
                child: PlaceTopDialog(),
              ));
        });
  }

  /// 置顶套餐选择弹窗
  Future showPlaceTopComboDialog() async {
    return await showGeneralDialog(
        context: context,
        pageBuilder: (context, anim1, anim2) {},
        barrierDismissible: true,
        barrierLabel: "",
        transitionDuration: Duration(milliseconds: 300),
        transitionBuilder: (context, anim1, anim2, child) {
          return Transform.scale(
              scale: anim1.value,
              child: Opacity(
                opacity: anim1.value,
                child: PlaceTopComboDialog(),
              ));
        });
  }

  void _forSubmitted() async {
    if (radioGroupValue == 1) {
      /// 置顶弹窗
      int value = await showPlaceTopDialog();
      if (value == PLACE_DIALOG_TOP) {
        /// 置顶付费
        _comboTopEntity = await showPlaceTopComboDialog();
        _publishMarket();
      } else if (value == PLACE_DIALOG_FREE) {
        /// 免费发布
        _comboTopEntity = null;
        _publishMarket();
      }
    } else if (radioGroupValue == 2) {
      /// 免费发布
      _comboTopEntity = null;
      _publishMarket();
    }
  }

  _preparePublish() async {
    if (isEmpty(_title)) {
      ToastUtils.show("请输入标题");
      return;
    }
    if (isEmpty(_companyName)) {
      ToastUtils.show("请输入公司名称");
      return;
    }
    if (isEmpty(_userName)) {
      ToastUtils.show("请输入联系人姓名");
      return;
    }
    if (!RegexUtil.isMobileExact(_phone)) {
      ToastUtils.show("请输入正确的联系电话");
      return;
    }
    if (isEmpty(_wechatNum)) {
      ToastUtils.show("请输入微信号");
      return;
    }
    if (isEmpty(_city)) {
      ToastUtils.show("请输入城市");
      return;
    }
    if (isEmpty(_industryName)) {
      ToastUtils.show("请选择行业");
      return;
    }

    if (isEmpty(_content)) {
      ToastUtils.show("请输入发布内容");
      return;
    }
    _forSubmitted();
  }

  /// 更新 [置顶、免费]按钮状态
  updateGroupValue(value) {
    if (mounted)
      setState(() {
        radioGroupValue = value;
      });
  }

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    return widget.marketType == AppConstant.MARKET_SUPPLY
        ? _initSupplSyFormData()
        : _initDemandFromData();
  }

  /// 供应表单
  Widget _initSupplSyFormData() {
    return SingleChildScrollView(
        physics: BouncingScrollPhysics(),
        child: Form(
            key: _formKey,
            child: Column(children: <Widget>[
              FormOptionItem(
                  title: "标题",
                  placeholder: "请输入标题内容",
                  content: _title ?? "",
                  inputOnly: true,
                  keyboardType: TextInputType.text,
                  onChangeCallback: (val) {
                    _title = val;
                  }),
              FormOptionItem(
                  title: "公司",
                  placeholder: "请输入公司名称",
                  content: _companyName ?? "",
                  inputOnly: true,
                  keyboardType: TextInputType.text,
                  onChangeCallback: (val) {
                    _companyName = val;
                  }),
              FormOptionItem(
                  title: "姓名",
                  placeholder: "请输入联系人姓名",
                  content: _userName ?? "",
                  inputOnly: true,
                  keyboardType: TextInputType.text,
                  onChangeCallback: (val) {
                    _userName = val;
                  }),
              FormOptionItem(
                  title: "电话",
                  placeholder: "请输入联系电话",
                  content: _phone ?? "",
                  inputOnly: true,
                  keyboardType: TextInputType.phone,
                  onChangeCallback: (val) {
                    _phone = val;
                  }),
              FormOptionItem(
                  title: "微信",
                  placeholder: "请输入微信号",
                  content: _wechatNum ?? "",
                  inputOnly: true,
                  keyboardType: TextInputType.number,
                  onChangeCallback: (val) {
                    _wechatNum = val;
                  }),
              FormOptionItem(
                  title: "位置",
                  placeholder: "请选择您所在城市",
                  content: _city ?? "",
                  selectCallback: () {
                    PickerUtils.showCityPicker(context,
                        clickCallBack: (codes, value) {
                      setState(() {
                        _cityCode = codes.last;
                        _city = value;
                      });
                    });
                  }),
              FormOptionItem(
                  title: "行业",
                  placeholder: "请选择行业类别",
                  content: _industryName ?? "",
                  selectCallback: () {
                    _getIndustryCategory().then((value) => {
                          PickerUtils.showStringPicker(context,
                              data: _industryDatas.map((e) => e.title).toList(),
                              clickCallBack: (index, val) {
                            setState(() {
                              _industryId = _industryDatas[index].id;
                              _industryName = _industryDatas[index].title;
                            });
                          })
                        });
                  }),
              FormOptionItem(
                  title: "参考价",
                  placeholder: "请输入参考价格（单位：元）",
                  content: _price ?? "",
                  keyboardType: TextInputType.number,
                  inputOnly: true,
                  inputFormatters: [
                    FilteringTextInputFormatter.allow(RegExp("[0-9.]")),
                  ],
                  onChangeCallback: (val) {
                    _price = val;
                  }),
              FormMultipleInputItem(
                  title: "内容",
                  placeholder: "请输入内容（不超过1000字）",
                  content: _content ?? "",
                  onChangeCallback: (val) {
                    _content = val;
                  }),
              _initImagesList(),
              _initRadioView(),
              _getSubmitBtn()
            ])));
  }

  /// 需求表单
  Widget _initDemandFromData() {
    return SingleChildScrollView(
        physics: BouncingScrollPhysics(),
        child: Form(
            key: _formKey,
            child: Column(children: <Widget>[
              FormOptionItem(
                  title: "标题",
                  placeholder: "请输入标题内容",
                  content: _title ?? "",
                  inputOnly: true,
                  keyboardType: TextInputType.text,
                  onChangeCallback: (val) {
                    _title = val;
                  }),
              FormOptionItem(
                  title: "公司",
                  placeholder: "请输入公司名称",
                  content: _companyName ?? "",
                  inputOnly: true,
                  keyboardType: TextInputType.text,
                  onChangeCallback: (val) {
                    _companyName = val;
                  }),
              FormOptionItem(
                  title: "姓名",
                  placeholder: "请输入联系人姓名",
                  content: _userName ?? "",
                  inputOnly: true,
                  keyboardType: TextInputType.text,
                  onChangeCallback: (val) {
                    _userName = val;
                  }),
              FormOptionItem(
                  title: "电话",
                  placeholder: "请输入联系电话",
                  content: _phone ?? "",
                  keyboardType: TextInputType.phone,
                  inputOnly: true,
                  onChangeCallback: (val) {
                    _phone = val;
                  }),
              FormOptionItem(
                  title: "微信",
                  placeholder: "请输入微信号",
                  content: _wechatNum ?? "",
                  inputOnly: true,
                  keyboardType: TextInputType.number,
                  onChangeCallback: (val) {
                    _wechatNum = val;
                  }),
              FormOptionItem(
                  title: "位置",
                  placeholder: "请选择您所在城市",
                  content: _city ?? "",
                  selectCallback: () {
                    PickerUtils.showCityPicker(context,
                        clickCallBack: (codes, value) {
                      setState(() {
                        _cityCode = codes.last;
                        _city = value;
                      });
                    });
                  }),
              FormOptionItem(
                  title: "行业",
                  placeholder: "请选择行业类别",
                  content: _industryName ?? "",
                  selectCallback: () {
                    _getIndustryCategory().then((value) => {
                          PickerUtils.showStringPicker(context,
                              data: _industryDatas.map((e) => e.title).toList(),
                              clickCallBack: (index, val) {
                            setState(() {
                              _industryId = _industryDatas[index].id;
                              _industryName = _industryDatas[index].title;
                            });
                            // _industryTextController.text = _selectIndustry.name;
                          })
                        });
                  }),
              FormMultipleInputItem(
                  title: "内容",
                  placeholder: "请输入内容（不超过1000字）",
                  content: _content ?? "",
                  onChangeCallback: (val) {
                    _content = val;
                  }),
              _initImagesList(),
              _initRadioView(),
              _getSubmitBtn()
            ])));
  }

  /// 添加的图片列表
  Widget _initImagesList() {
    return Container(
        margin: EdgeInsets.symmetric(
            horizontal: ScreenAdapter.width(30),
            vertical: ScreenAdapter.height(20)),
        child: GridView.builder(
            itemCount: _selectImageFile.length + 1,
            //SliverGridDelegateWithFixedCrossAxisCount 构建一个横轴固定数量Widget
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                //横轴元素个数
                crossAxisCount: 4,
                //纵轴间距
                mainAxisSpacing: ScreenAdapter.height(30),
                //横轴间距
                crossAxisSpacing: ScreenAdapter.width(20),
                //子组件宽高长度比例
                childAspectRatio: 1.0),
            itemBuilder: (BuildContext context, int index) {
              bool isAdd = index < _selectImageFile.length ? false : true;
              File file = index < _selectImageFile.length
                  ? _selectImageFile[index]
                  : null;
              return _getPicturesItem(
                  file: file,
                  isAdd: isAdd,
                  clickCallback: () {
                    ImagePickerUtils.getImage(PICKER_PHOTO).then((value) {
                      if (value != null) {
                        setState(() {
                          _selectImageFile.add(value);
                        });
                      }
                    });
                  },
                  deleteCallback: () {
                    setState(() {
                      _selectImageFile.removeAt(index);
                    });
                  });
            }));
  }

  /// 置顶 / 付费
  Widget _initRadioView() {
    return Row(children: <Widget>[
      Row(
        children: [
          Radio(
              value: 1,
              groupValue: radioGroupValue,
              activeColor: ThemeColors.colorType6,
              onChanged: (T) {
                updateGroupValue(T);
              }),
          Text("置顶")
        ],
      ),
      Row(children: [
        Radio(
            value: 2,
            groupValue: radioGroupValue,
            activeColor: ThemeColors.colorType6,
            onChanged: (T) {
              updateGroupValue(T);
            }),
        Text("免费")
      ]),
    ]);
  }

  /// 图片Item
  Widget _getPicturesItem(
      {File file,
      bool isAdd,
      VoidCallback clickCallback,
      VoidCallback deleteCallback}) {
    return Stack(
      children: <Widget>[
        GestureDetector(
          onTap: isAdd ? clickCallback : null,
          child: Container(
              width: double.infinity,
              height: double.infinity,
              margin: EdgeInsets.symmetric(
                  vertical: ScreenAdapter.height(10),
                  horizontal: ScreenAdapter.width(10)),
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(ScreenAdapter.width(12)),
                  child: isAdd
                      ? Image.asset(
                          RPath.imgPath + "img_add_placeholder.png",
                          fit: BoxFit.fill,
                        )
                      : Image.file(file, fit: BoxFit.cover))),
        ),
        !isAdd
            ? Positioned(
                right: 0,
                top: 0,
                child: GestureDetector(
                  onTap: deleteCallback,
                  child: Container(
                      child: Image.asset(RPath.imgPath + "icon_close_x.png",
                          width: ScreenAdapter.width(20),
                          height: ScreenAdapter.width(20))),
                ),
              )
            : Container()
      ],
    );
  }

  /// 提交按钮
  Widget _getSubmitBtn() {
    return Container(
        height: ScreenAdapter.height(90),
        width: double.infinity,
        margin: EdgeInsets.symmetric(
            vertical: ScreenAdapter.height(50),
            horizontal: ScreenAdapter.width(30)),
        decoration: BoxDecoration(
            color: ThemeColors.colorType6,
            borderRadius: BorderRadius.circular(ScreenAdapter.width(14))),
        child: FlatButton(
            onPressed: () {
              _preparePublish();
            },
            child: Text("确定",
                style: TextStyle(
                    color: ThemeColors.colorWhite,
                    fontSize: ScreenAdapter.sp(32)))));
  }
}
